package com.cssl.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cssl.common.constant.auth.AuthConstant;
import com.cssl.common.utils.HttpUtils;
import com.cssl.common.utils.R;
import com.cssl.common.vo.auth.GiteeUser;
import com.cssl.common.vo.auth.MemberResponseVO;
import com.cssl.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception{
        Map<String,String> header = new HashMap<>();
        Map<String,String> query = new HashMap<>();



        Map<String,String> map = new HashMap<>();
        map.put("client_id","d056ccb748442b877883a9326db8d53b8b0efb4352a9a7fb4e23c5f96d913cab");
        map.put("client_secret","4c18b4248cd72ca87d9d088ad9ca7409cd2d6efd3d6a6aca9198ae6f139fb6ec");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("code",code);
        //1、根据code换取accessToken；
        HttpResponse response = com.cssl.common.utils.HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", header, query, map);
        System.out.println(response.getStatusLine().getStatusCode() );
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到accessToken

            String json = EntityUtils.toString(response.getEntity());
            System.out.println("获取到的token为：" + json);
            JSONObject jsonObject = JSON.parseObject(json);
            String access_token = jsonObject.getString("access_token");
            System.out.println("获取到的access_token：" + access_token);


            //gitee还需要再去请求user去获取数据
//            GiteeUser giteeUser =  giteeComponent.getGiteeUser(json);
            String urluser = "https://gitee.com/api/v5/user?access_token=" + access_token;
            HttpClient httpClientUser = HttpClientBuilder.create().build();
            HttpGet httpPostUser = new HttpGet(urluser);           //记得用httpGet请求，否则会405拒绝请求
            HttpResponse responseUser = httpClientUser.execute(httpPostUser);

            GiteeUser giteeUser = new GiteeUser();
            String user = EntityUtils.toString(responseUser.getEntity());
            System.out.println("gitee用户信息"+user);

            JSONObject jsonObjectUser = JSON.parseObject(user);
            String id = jsonObjectUser.getString("id");
            System.out.println(id);
            giteeUser.setId(id);
            String name = jsonObjectUser.getString("name");
            System.out.println(name);
            giteeUser.setName(name);
            String bio = jsonObjectUser.getString("bio");
            System.out.println(bio);
            giteeUser.setBio(bio);

            //知道当前是哪个社交用户登录成功
            //1、当前用户如果是第一次进网站，就自动注册进来（为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R r = memberFeignService.oauth2Login(giteeUser);
            if (r.getCode() == 0) {
                MemberResponseVO memberRespVo = r.getData(new TypeReference<MemberResponseVO>() {
                });
                System.out.println("登录成功，用户信息：" + memberRespVo);
                log.info("登录成功，用户信息：" + memberRespVo);
                //TODO 1、默认发的令牌 session=dadas,作用域只是当前域，（解决子域与父域session共享问题）
                //TODO 2、使用json的序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthConstant.LOGIN_USER, memberRespVo);
                //2、登录成功就跳回首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://gulimall.com/login.html";
        }
    }
}
